package tt.dz.service.impl;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import tt.dz.common.Constants;
import tt.dz.common.PublicFunc;
import tt.dz.dao.pro.UserMemberDao;
import tt.dz.dao.pro.UserPayCardDao;
import tt.dz.dao.pro.UserWalletDao;
import tt.dz.entity.UserMember;
import tt.dz.entity.UserPayCard;
import tt.dz.entity.UserWallet;
import tt.dz.service.UserMemberService;

/**
 * 会员信息业务接口实现类
 * @author xielf
 *
 */
@Service
public class UserMemberServiceImpl implements UserMemberService {

	/**会员信息Dao*/
	@Resource
	UserMemberDao<UserMember> userMemberDao;
	
	/**用户支付卡Dao*/
	@Resource
	UserPayCardDao<UserPayCard> userPayCardDao;
	
	/**用户账户Dao*/
	@Resource
	UserWalletDao<UserWallet> userWalletDao;
	
	@Override
	public List<UserMember> getUserInfoList(Integer pageNo, Integer pageSize) {
		return userMemberDao.findUserMemberPaging(pageNo, pageSize);
	}
	
	@Override
	public List<UserMember> getUserInfoByUserId(String userid) {
		List<UserMember> userMembers = userMemberDao.findUserMemberByUserIds(userid);
		return userMembers;
	}
	
	@Override
	public UserMember getUserInfoByUserId(Integer userid) {
		return userMemberDao.findUserMemberByUserId(userid);
	}

	@Override
	public UserMember getUserInfoByPayCard(String cardNum) {
		
		//查找用户支付卡信息
		UserPayCard userPayCard = userPayCardDao.findUserPayCardByCardNum(cardNum);
		if(userPayCard!=null){
			return userMemberDao.findUserMemberByUserId(userPayCard.getUser_id());
		}
		return null;
	}
	
	@Override
	public String register(UserMember userMember,String areaNum) {
		
		//如果此用户名已经存在
		List<UserMember> members = userMemberDao.existsUserInfoByUserName(userMember.getUsername());
		if(members!=null && members.size()>0){
			return Constants.JsonResponseCode.USER_EXISTS;
		}
		//设置phpssouid
		userMember.setPhpssouid(userMemberDao.findMax_phpssouid()+1);
		userMember.setRegdate(new Date());
		userMember.setActivated("1");
		userMember.setNickname("昵称");
		userMember.setIslock(1);
//		userMember.setAmount(0.00);
//		userMember.setAreaid(0);
//		userMember.setGroupid(0);
//		userMember.setPoint(0);
//		userMember.setModelid(0);
		userMember.setLoginnum(0);
		//不存在
		Serializable serializable = userMemberDao.save(userMember);
		
		/**用户卡*/
		UserPayCard userPayCard = new UserPayCard();
		userPayCard.setCard_bing_num(188);
		userPayCard.setCard_status(1);
		userPayCard.setCard_type_num(8);
		userPayCard.setUser_id(userMember.getUserid());
		userPayCard.setArea_num(Integer.parseInt(areaNum));
		//流水号码
		Integer serialNum = userPayCardDao.getMaxSerialNumByAreaNum(Integer.parseInt(areaNum));
		String serialNumStr = "";
		//如果本地区流水没有
		if(serialNum==0){
			serialNumStr="0000000001";
		}
		//如果有
		else{
			serialNum+=1;
			//得到int流水长度
			Integer serialLength = (serialNum+"").length();
			//前面累加“0”
			for (int i = 0; i < 10-serialLength; i++) {
				serialNumStr+="0";
			}
			//链接int流水 获取最终流水
			serialNumStr+=serialNum;
		}
		userPayCard.setSerial_num(serialNumStr);
		userPayCard.setPhone_num(userMember.getMobile());
		
		//校验位算法
		String preCard = "18808"+areaNum+userPayCard.getSerial_num();
		Integer checkOutNum = PublicFunc.checkOutUserCardByte(preCard);
		System.out.println(preCard+checkOutNum);
		userPayCard.setUser_card(preCard+checkOutNum);
		userPayCard.setAdd_time(new Date());
		userPayCard.setActive_time(new Date());
		//校验号码
		userPayCard.setVerify_num(checkOutNum);
		userPayCardDao.save(userPayCard);
		
		/**用户账户*/
		UserWallet userWallet = new UserWallet();
		userWallet.setBalance(0.00);
		userWallet.setFreeze_sum(0.00);
		userWallet.setReg_time(userMember.getRegdate());
		userWallet.setUser_id(userMember.getUserid());
		userWallet.setUpdate_time(new Date());
		userWalletDao.save(userWallet);
		
		if(serializable!=null){
			return Constants.JsonResponseCode.SUCCESS;
		}
		return Constants.JsonResponseCode.FAIL;
	}

	@Override
	public UserMember login(String userName,String password,Integer areaNum) {
		
		//如果此用户名存在
		List<UserMember> members = userMemberDao.existsUserInfoByUserName(userName);
		if(members!=null && members.size()>0){
			UserMember userMember = members.get(0);
			//得到数据库密码KEY
			String encrypt = userMember.getEncrypt();
			//密码MD5编码
			String cipherPassword = PublicFunc.MD5(PublicFunc.MD5(password)+encrypt);
			//匹配密码是否相同
			if(userMember.getPassword().equals(cipherPassword)){
				
				//查询用户支付卡号
				UserPayCard resultUserPayCard = userPayCardDao.findUserPayCardByUserId(userMember.getUserid());
				//如果不存在
				if(resultUserPayCard==null){
					UserPayCard userPayCard = new UserPayCard();
					userPayCard.setCard_bing_num(188);
					userPayCard.setCard_status(1);
					userPayCard.setCard_type_num(8);
					userPayCard.setUser_id(userMember.getUserid());
					//流水号码
					Integer serialNum = userPayCardDao.getMaxSerialNumByAreaNum(Integer.valueOf(areaNum));
					String serialNumStr = "";
					//如果本地区流水没有
					if(serialNum==0){
						serialNumStr="0000000001";
					}
					//如果有
					else{
						serialNum+=1;
						//得到int流水长度
						Integer serialLength = (serialNum+"").length();
						//前面累加“0”
						for (int i = 0; i < 10-serialLength; i++) {
							serialNumStr+="0";
						}
						//链接int流水 获取最终流水
						serialNumStr+=serialNum;
					}
					userPayCard.setSerial_num(serialNumStr);
					userPayCard.setPhone_num(userMember.getMobile());
					//校验位算法
					String preCard = "18808"+areaNum+userPayCard.getSerial_num();
					Integer checkOutNum = PublicFunc.checkOutUserCardByte(preCard);
					userPayCard.setUser_card(preCard+checkOutNum);
					userPayCard.setAdd_time(new Date());
					userPayCard.setActive_time(new Date());
					//校验号码
					userPayCard.setVerify_num(checkOutNum);
					userPayCardDao.save(userPayCard);
				}
				return userMember;
			}
		}
		//用户名密码错误
		return null;
	}

	@Override
	public String updateUserLocation(Integer userId,Double lat,Double lng) {
		
		UserMember waitOpUserMember = userMemberDao.findUserMemberByUserId(userId);
		if(waitOpUserMember!=null){
			//设置经纬度
			waitOpUserMember.setLat(lat);
			waitOpUserMember.setLng(lng);
			this.updateUserInfo(waitOpUserMember);
			return Constants.JsonResponseCode.SUCCESS;
		}
		else{
			return Constants.JsonResponseCode.USER_NOT_EXISTS;
		}
	}

	@Override
	public void updateUserInfo(UserMember userMember) {
		
		//根据对象userid查询出对象信息
		UserMember userMember1 = userMemberDao.findUserMemberByUserId(userMember.getUserid());
		//设置修改资料
		userMember1.setNickname(userMember.getNickname());
		userMember1.setSignature(userMember.getSignature());
//		userMember1.setCartype(userMember.getCartype());
		userMember1.setSex(userMember.getSex());
//		userMember1.setChargingtype(userMember.getChargingtype());
		userMember1.setPhotovision(userMember.getPhotovision());
		userMember1.setAddress(userMember.getAddress());
		
		if(userMember.getPhpssouid()!=null && !"".equals(userMember.getPhpssouid()))
		{
			userMember.setHeadpath("phpsso_server/uploadfile/avatar/1/1/"+userMember.getPhpssouid());
		}
		
		//修改对象
		userMemberDao.update(userMember1);
	}

	@Override
	public void physicallyDeleteUserRelationById(Integer userId) {
		
		//用户信息
		UserMember userMember = userMemberDao.findUserMemberByUserId(userId);
		//用户钱包
		UserWallet userWallet = userWalletDao.findUserWalletByUserId(userId);
		//用户卡信息
		UserPayCard userPayCard = userPayCardDao.findUserPayCardByUserId(userId);

		if(userMember!=null){
			userMemberDao.physicallyDelete(userMember);
		}
		if(userWallet!=null){
			userWalletDao.physicallyDelete(userWallet);
		}
		if(userPayCard!=null){
			userMemberDao.physicallyDelete(userPayCard);
		}
	}

	@Override
	public String updatePassword(Integer userId, String oldPassword,
			String newPassword) {
		UserMember userMember = userMemberDao.findUserMemberByUserId(userId);
		if(userMember!=null){
			//得到数据库密码KEY
			String encrypt = userMember.getEncrypt();
			//密码MD5编码
			String cipherPassword = PublicFunc.MD5(PublicFunc.MD5(oldPassword)+encrypt);
			//匹配密码是否相同
			if(!userMember.getPassword().equals(cipherPassword)){
				return Constants.JsonResponseCode.OLD_PWD_ERROR;
			}
			else{
				newPassword = PublicFunc.MD5(PublicFunc.MD5(newPassword)+encrypt);
				userMember.setPassword(newPassword);
				userMemberDao.update(userMember);
				return Constants.JsonResponseCode.SUCCESS;
			}
		}
		return Constants.JsonResponseCode.USER_NOT_EXISTS;
	}

	@Override
	public List<UserMember> getNearUserInfo(Double lat, Double lng,Integer pageNo,Integer pageSize) {
		return userMemberDao.findNearUserMember(lat, lng, pageNo, pageSize);
	}

	@Override
	public Double getDistanceByUserIdAndLatLng(Double lat, Double lng,
			Integer userId) {
		return userMemberDao.findDistanceByUserIdAndLatLng(lat, lng, userId);
	}

	@Override
	public boolean judgeUserExistsByPhone(String phone) {
		UserMember userMember = userMemberDao.findUserMemberByPhone(phone);
		return userMember==null ? false : true;
	}

	@Override
	public List<UserMember> getUserMemberByImUserName(String chatUserName) {
		return userMemberDao.findUserMemberByChatUserName(chatUserName);
	}

	@Override
	public boolean updatePasswordByPhone(String phone, String password) {
		UserMember userMember = userMemberDao.findUserMemberByPhone(phone);
		if(userMember==null){
			return false;
		}
		userMember.setPassword(PublicFunc.MD5(PublicFunc.MD5(password)+userMember.getEncrypt()));
		userMemberDao.update(userMember);
		return true;
	}

	@Override
	public List<UserMember> getUserInfoFuzzyByPhone(String phone,int pageNo,int pageSize) {
		return userMemberDao.findUserInfoFuzzyByPhone(phone, pageNo, pageSize);
	}

	@Override
	public UserMember getUserInfoByPhone(String phone) {
		return userMemberDao.findUserByPhone(phone);
	}
}
